﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;

namespace NetfractionHub.LocalMachine.BotCommands.Handler
{
    [CommandHandler("regupdate")]
    public class UpdateRegistration : CommandHandler
    {
        public override BotReturnStatus HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
        {
            if (message.StringArguments.Count == 2)
            {
                if (!message.StringArguments.ContainsKey("user"))
                    return new BotReturnStatus(false, "Missing argument 'user'.");

                if (!message.StringArguments.ContainsKey("newcid"))
                    return new BotReturnStatus(false, "Missing argument 'newcid'.");

                return UpdateRegisteredClientId(source, message.StringArguments["user"], message.StringArguments["cid"]);
            }
            else
                return false;
        }

        private BotReturnStatus UpdateRegisteredClientId(NetfractionHub.RemoteMachine.Node source, string username, string clientId)
        {
            Security.Identity ident = Security.IdentityManager.GetIdentityByName(username);

            if (ident == null)
                return new BotReturnStatus(false, string.Format("Cannot update registration, the user '{0}' is not registered.", username));

            if (!Security.Permission.HasPermission(source.SecurityIdentity, typeof(Security.Permissions.UpdateUserPermission)))
                return new BotReturnStatus(false, Security.Permission.GetDeniedString(typeof(Security.Permissions.UpdateUserPermission)));

            ident.ClientId = clientId;
            if (Security.IdentityManager.UpdateClientId(username, ident))
                return new BotReturnStatus(true, "Registration Update Successful.");
            else
                return new BotReturnStatus(false, "Registration Update Failed.");
        }
    }
}
